package it.polimi.swKnights.SWIMv2.servlets.search;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.searchEngine.FriendSearchRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class NormalFriendSearchProceed
 */
public class NormalFriendSearchProceed extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		String userName = (String) request.getSession()
				.getAttribute("userName");
		String password = (String) request.getSession()
				.getAttribute("password");

		String query = (String) request.getParameter("query");
		
		FriendSearchRemote remSearch = this.lookUp(FriendSearchRemote.class);

		String errorPage = "./siteHome?error=";

		try
		{
			List<Map<String, String>> lstFriends = remSearch
					.searchAmongFriends(userName, password, query);

			request.setAttribute("userResultMap", lstFriends);
			
			System.err.println("trovati: " + lstFriends.size());
			System.err.println("ecco chi ho trovato: " + lstFriends);

			request.getRequestDispatcher("WEB-INF/friends/UserFriends.jsp")
					.forward(request, response);
		}
		catch (LoginFailException e)
		{
			response.sendRedirect(errorPage + Errors.session);
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect(errorPage + Errors.session);
		}
		catch(EJBException e)
		{
			response.sendRedirect("./friends");
		}

	}

}
